package org.example.service;

import org.example.mapper.UserMapper;
import org.example.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;

@Service
public class UserServiceImpl implements UserService{

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private HttpSession session;

    @Override
    public ModelAndView login(User user) {
        ModelAndView modelAndView = new ModelAndView();
        User dUser = userMapper.selectByName(user.getName());

        if (dUser == null) {
            modelAndView.addObject("alert", "用户名不存在");
            modelAndView.setViewName("login");
        } else if (!dUser.getPassword().equals(user.getPassword())) {
            modelAndView.addObject("alert", "密码错误");
            modelAndView.setViewName("login");
        } else {
            session.setAttribute("user", dUser);
            modelAndView.setViewName("redirect:/app");
        }

        return modelAndView;
    }

    @Override
    public ModelAndView register(User user) {
        ModelAndView modelAndView = new ModelAndView();

        if (user.getPassword() == null || user.getPassword().length() < 6){
            modelAndView.addObject("alert", "密码长度不能小于6");
            modelAndView.setViewName("register");
        } else if (user.getName() == null || user.getName().length() < 3) {
            modelAndView.addObject("alert", "用户名长度不能小于3");
            modelAndView.setViewName("register");
        } else {
            User dUser = userMapper.selectByName(user.getName());
            if (dUser != null) {
                modelAndView.addObject("alert", "用户名已存在");
                modelAndView.setViewName("register");
                return modelAndView;
            }
            userMapper.add(user);

            session.setAttribute("user", user);
            modelAndView.setViewName("redirect:/app");
        }
        return modelAndView;
    }


}
